package com.ts.api.module.common.service.impl;

import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.random.RandomCodeUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.redis.SmsRedisKey;
import com.ts.api.exp.BizException;
import com.ts.api.http.sms.SmsProvider;
import com.ts.api.module.common.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsProvider smsProvider;

    @Override
    public void sendCode(String phone) {
        if (SmsRedisKey.PHONE_CODE.exist(phone)) {
            throw new BizException(BizEnum.SMS_DUPLICATE);
        }

        Object phoneCount = SmsRedisKey.PHONE_COUNT.get(phone);
        if (phoneCount == null) {
            SmsRedisKey.PHONE_COUNT.setForSeconds(phone, 1, DateUtils.getTomorrowMidnightMillis() / 1000);
        } else {
            //  阈值
            Long increment = SmsRedisKey.PHONE_COUNT.increment(phone);
            if (increment > 10L) {
                throw new BizException(BizEnum.SMS_SEND_MAX);
            }
        }
        String code = RandomCodeUtils.generateSixDigitStr();

        this.smsProvider.sendCode(phone, code);

        //  存入验证码有效期三分钟
        SmsRedisKey.PHONE_CODE.setForMinutes(phone, code, 3L);
    }

    @Override
    public void validSmsCode(String phone, String code) {
        String cacheCode = SmsRedisKey.PHONE_CODE.get(phone, String.class);
        Assert.isNotEmptyThrows(cacheCode, new BizException(BizEnum.SMS_EMPTY));
        Assert.isTrueThrows(Eq.str(cacheCode, code), new BizException(BizEnum.SMS_VALID_ERROR));
    }

    @Override
    public void sendCustomerNotice(String phone, String orgName) {
        this.smsProvider.sendCustomerNotice(phone, orgName);
    }

    @Override
    public void sendCustomerNoticeForIpOffModule(String phone, String orgName) {
        this.smsProvider.sendCustomerNoticeForIpOffModule(phone, orgName);
    }

    @Override
    public void sendCrmNotice(String phone, String orgName) {
        this.smsProvider.sendCrmNotice(phone, orgName);
    }
}
